package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.mapper.ControlProblemFindingMapper;
import com.bf.electroplating.pojo.dto.problem.ControlProblemFindingAddDTO;
import com.bf.electroplating.pojo.dto.problem.ControlProblemFindingQueryDTO;
import com.bf.electroplating.pojo.dto.problem.ControlProblemFindingUpdateDTO;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.ControlProblemFinding;
import com.bf.electroplating.pojo.entity.PubAttachmentRel;
import com.bf.electroplating.pojo.enums.AttModuleEnums;
import com.bf.electroplating.pojo.enums.ProblemTypeEnum;
import com.bf.electroplating.pojo.enums.RectificationStatusEnum;
import com.bf.electroplating.pojo.vo.problem.ControlProblemFindingVO;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.ControlProblemFindingService;
import com.bf.electroplating.service.PubAttachmentRelService;
import com.bf.electroplating.service.PubAttachmentService;
import com.bf.electroplating.util.easyexcel.excel.problem.ProblemFindingExcel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 15451
 * @description 针对表【control_problem_finding(问题发现表)】的数据库操作Service实现
 * @createDate 2025-06-23 14:18:57
 */
@Slf4j
@Service
public class ControlProblemFindingServiceImpl extends ServiceImpl<ControlProblemFindingMapper, ControlProblemFinding>
        implements ControlProblemFindingService {

    @Resource
    private PubAttachmentService attachmentService;

    @Resource
    private PubAttachmentRelService attachmentRelService;

    @Resource
    private ComCompanyService companyService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(ControlProblemFindingAddDTO dto) {
        ControlProblemFinding entity = new ControlProblemFinding();
        BeanUtils.copyProperties(dto, entity);
        entity.setRectificationStatus(RectificationStatusEnum.AWAIT.getCode());

        // 转换时间格式
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            entity.setDiscoveryTime(sdf.parse(dto.getDiscoveryTime()));
            entity.setPlanCompletionTime(sdf.parse(dto.getPlanCompletionTime()));
        } catch (ParseException e) {
            log.error("日期解析失败：" + e.getMessage());
            throw new RuntimeException("日期格式错误");
        }

        // 保存实体
        save(entity);

        // 保存问题照片
        if (dto.getPhotoList() != null && !dto.getPhotoList().isEmpty()) {
            attachmentService.saveWholeAttachmentRel(dto.getPhotoList(), entity.getId(), AttModuleEnums.PROBLEM_PHOTO.getCode());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ControlProblemFindingUpdateDTO dto) {
        ControlProblemFinding entity = getById(dto.getId());
        if (entity == null) {
            throw new RuntimeException("记录不存在");
        }

        BeanUtils.copyProperties(dto, entity);

        // 转换时间格式
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if (StringUtils.isNotBlank(dto.getPlanCompletionTime())) {
                entity.setPlanCompletionTime(sdf.parse(dto.getPlanCompletionTime()));
            }
        } catch (ParseException e) {
            log.error("日期解析失败：" + e.getMessage());
            throw new RuntimeException("日期格式错误");
        }

        // 更新实体
        updateById(entity);

        // 更新问题照片
        attachmentRelService.remove(new LambdaQueryWrapper<PubAttachmentRel>()
                .eq(PubAttachmentRel::getStorePath, AttModuleEnums.PROBLEM_PHOTO.getCode())
                .eq(PubAttachmentRel::getRelationId, entity.getId()));
        if (dto.getPhotoList() != null && !dto.getPhotoList().isEmpty()) {
            attachmentService.saveWholeAttachmentRel(dto.getPhotoList(), entity.getId(), AttModuleEnums.PROBLEM_PHOTO.getCode());
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String id) {
        removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<String> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public ControlProblemFindingVO detail(String id) {
        ControlProblemFinding entity = getById(id);
        if (entity == null) {
            return null;
        }
        return convertToVO(entity);
    }

    @Override
    public Page<ControlProblemFindingVO> page(ControlProblemFindingQueryDTO dto) {
        Page<ControlProblemFinding> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        LambdaQueryWrapper<ControlProblemFinding> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(dto.getCompanyId()), ControlProblemFinding::getCompanyId, dto.getCompanyId())
                .eq(StringUtils.isNotBlank(dto.getProblemType()), ControlProblemFinding::getProblemType, dto.getProblemType());

        // 如果有计划完成时间查询
        if (StringUtils.isNotBlank(dto.getPlanCompletionTime())) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                wrapper.eq(ControlProblemFinding::getPlanCompletionTime, sdf.parse(dto.getPlanCompletionTime()));
            } catch (ParseException e) {
                log.error("日期解析失败：" + e.getMessage());
            }
        }

        wrapper.orderByDesc(ControlProblemFinding::getCreateTime);

        Page<ControlProblemFinding> result = page(page, wrapper);

        List<ControlProblemFindingVO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        Page<ControlProblemFindingVO> voPage = new Page<>();
        BeanUtils.copyProperties(result, voPage, "records");
        voPage.setRecords(voList);
        return voPage;
    }

    private ControlProblemFindingVO convertToVO(ControlProblemFinding entity) {
        if (entity == null) {
            return null;
        }

        ControlProblemFindingVO vo = new ControlProblemFindingVO();
        BeanUtils.copyProperties(entity, vo);
        vo.setRectificationStatusString(RectificationStatusEnum.getDesc(entity.getRectificationStatus()));
        vo.setCompanyName(companyService.getById(entity.getCompanyId()).getCompanyName());

        // 转换时间格式
        vo.setDiscoveryTime(getDateStr(entity.getDiscoveryTime()));
        vo.setPlanCompletionTime(getDateStr(entity.getPlanCompletionTime()));
        vo.setProblemTypeString(ProblemTypeEnum.getDesc(entity.getProblemType()));

        // 获取问题照片
        vo.setPhotoList(attachmentService.getWholeFile(entity.getId(), AttModuleEnums.PROBLEM_PHOTO.getCode()));
        // 获取整改照片
        vo.setRectificationPhotoList(attachmentService.getWholeFile(entity.getId(), AttModuleEnums.PROBLEM_RECTIFICATION_PHOTO.getCode()));

        return vo;
    }

    private String getDateStr(Date date) {
        if (date == null) {
            return null;
        }
        LocalDate localDate = date.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return formatter.format(localDate);
    }

    @Override
    public void saveBatch(List<ProblemFindingExcel> dataList) {
        dataList.forEach(data -> {
            ControlProblemFinding entity = new ControlProblemFinding();
            ComCompany comCompany = companyService.getOne(new LambdaQueryWrapper<ComCompany>().eq(ComCompany::getCompanyName, data.getCompanyName()), false);
            entity.setCompanyId(comCompany != null ? comCompany.getId() : null);
            entity.setProblemType(ProblemTypeEnum.getCode(data.getProblemType()));
            entity.setRectificationStatus(RectificationStatusEnum.AWAIT.getCode());
            entity.setProblemLocation(data.getProblemLocation());
            entity.setProblemDescription(data.getProblemDescription());
            entity.setDiscoveryTime(data.getDiscoveryTime());
            entity.setPlanCompletionTime(data.getPlanCompletionTime());
            save(entity);
            data.getImages().forEach(image -> {
                PubAttachmentRel attachmentRel = new PubAttachmentRel();
                attachmentRel.setAttId(image);
                attachmentRel.setRelationId(entity.getId());
                attachmentRel.setStorePath(AttModuleEnums.PROBLEM_PHOTO.getCode());
                attachmentRelService.save(attachmentRel);
            });
        });
    }
}




